<?php


namespace App\Http\Controllers\Admin;

use App\Repository\RolesRepository;
use App\Repository\AdminHasRolesRepository;
use App\Repository\AdminRepository;
use App\Http\Requests\AdminRequest;
use App\Models\Admin\Admin;
//use app\models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use mysql_xdevapi\Exception;

class AdminController extends BaseController
{
    /**
     * 管理员列表
     * @param Admin $users
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author:
     * @date: 2019/5/17 15:22
     */
    public function index(Request $request,Admin $users)
    {
        $params = $request->except('_token');
        $where = [];
        if(isset($params['keywords'])){
            $where = [
                        ['name','like','%'.$params['keywords'].'%','or'],
                        ['nick_name','like','%'.$params['keywords'].'%','or'],
                        ['mobile','like','%'.$params['keywords'].'%','or'],
                        ['email','like','%'.$params['keywords'].'%','or']
                     ];
        }
        $usersList = $users->getUsers($where);
        return view('admin.admin.index',[
            'request'=>$request,
            'search' =>$params,
            'usersList'=>$usersList
        ]);
    }

    /**
     *  添加用户模板
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author:
     * @date: 2019/5/20 19:14
     */
    public function add(RolesRepository $rolesRepository)
    {
        return view('admin.admin.add',[
            'roles' => $rolesRepository->allRoles()
        ]);
    }

    /**
     * 添加用户操作
     * @param AdminRequest $request
     * @param AdminRepository $users
     * @param AdminHasRolesRepository $userHasRolesRepository
     * @return false|string
     * @throws \Exception
     * @author:
     * @date: 2019/5/24 18:00
     */
    public function doAdd(AdminRequest $request, AdminRepository $users, AdminHasRolesRepository $userHasRolesRepository)
    {
        $params                 = $request->except(['_token','password_confirmation']);
        $role_id                = $params['role_id'];
        $params['password']     = \Hash::make($params['password']);
        unset($params['role_id']);
        DB::beginTransaction();
        try{
            $addUsers       = $users->store($params);
            $userHasRole    = $userHasRolesRepository->add($addUsers,$role_id);
            if(!$addUsers || !$userHasRole){
                throw new \Exception('数据库操作异常');
            }
        }catch (\Exception $e){
            DB::rollBack();
            return $this->errorReturn(10001,$e->getMessage());
        }
        DB::commit();
        return $this->successReturn();
    }

    /**
     * 用户详情
     * @param $id 用户id
     * @param AdminRepository $usersRepository 用户信息查找
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author:
     * @date: 2019/5/20 19:15
     */
    public function edit($id, AdminRepository $usersRepository, Admin $users, RolesRepository $rolesRepository)
    {

        $roles          = [];
        $userHasRoles   = $users->find($id)->hasRoles;
        foreach ($userHasRoles as $key=>$value){
            $roles[$key]= $value->role_id;
        }
        $userInfo       = $usersRepository->get($id);
        return view('admin.admin.edit',[
            'userInfo'  => $userInfo,
            'rolesIds'  => $roles,
            'roles'     => $rolesRepository->allRoles()
        ]);
    }

    /**
     * 更新用户信息
     * @param AdminRequest $request
     * @param AdminRepository $usersRepository
     * @return false|string
     * @author:
     * @date: 2019/5/20 19:50
     */
    public function update(AdminRequest $request, AdminRepository $usersRepository, AdminHasRolesRepository $userHasRolesRepository)
    {
        $params = $request->except(['_token','password_confirmation']);
        if($params['id'] != 1){
            $roleIds = $params['role_id'];
            unset($params['role_id']);
            if(!empty($params['password'])){
                $params['password'] = \Hash::make($params['password']);
            }else{
                unset($params['password']);
            }
            DB::beginTransaction();
            try{
                $deleteRoles = $userHasRolesRepository->delete($params['id']);
                $updateUsers = $usersRepository->update($params);
                $updateRoles = $userHasRolesRepository->add($params['id'],$roleIds);
                if(!$deleteRoles || !$updateRoles || !$updateUsers){
                    throw new \Exception('用户信息编辑出错');
                }
            }catch (\Exception $e){
                DB::rollBack();
                return $this->errorReturn(10001,$e->getMessage());
            }
            DB::commit();
            return $this->successReturn();
        }
        unset($params['role_id']);
        $params['password'] = \Hash::make($params['password']);
        return  $usersRepository->update($params) ? $this->successReturn() : $this->errorReturn(10001,'用户信息编辑出错');

    }

    /**
     * 删除用户信息
     * @param Request $request
     * @param AdminRepository $usersRepository
     * @return false|string
     * @author:
     * @date: 2019/5/20 20:27
     */
    public function delete(Request $request, AdminRepository $usersRepository)
    {
        if($request->id == 1){
            return $this->errorReturn(10001,'超级管理员不得删除');
        };
        return $usersRepository->delete($request->id) ? $this->successReturn() : $this->errorReturn();

    }

    /**
     * 用户拉黑
     * @param Request $request
     * @param AdminRepository $usersRepository
     * @return false|string
     * @author:
     * @date: 2019/5/22 15:42
     */
    public function pullBack(Request $request, AdminRepository $usersRepository)
    {
        $userStatus = 1;
        if($request->post('type') == 1){
            $userStatus = 0;
        }
        if($request->id == 1){
            return $this->errorReturn(10001,'超级管理员不得删除');
        };
        return $usersRepository->pullBlack($request->id,$userStatus) ? $this->successReturn() : $this->errorReturn(10001,'操作异常');
    }

    public function editHeadPortrait()
    {
        return view('admin.edit_head_portrait');
    }
}
